package cn.anyubao.blog.common;


import cn.anyubao.blog.enums.CustomStatusEnum;
import cn.anyubao.blog.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.lang.reflect.ParameterizedType;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author huqilang
 */
public abstract class AbstractService<T extends BaseModel> implements BaseService<T> {

    private static final Logger log = LoggerFactory.getLogger(AbstractService.class);

    @Autowired
    private ApplicationContext applicationContext;

    protected Class<T> modelClass;

    protected BaseMapper<T> baseMapper;

    private static final String SQL_WHERE_DESC = "【SQL查询】查询条件:{}={}";


    public AbstractService() {
    }

    @PostConstruct
    public void initBaseDao() {
        ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
        this.modelClass = (Class)pt.getActualTypeArguments()[0];
        this.baseMapper = (BaseMapper)this.applicationContext.getBean(CommonUtils.getDefaultBeanName(this.modelClass.getSimpleName()) + "Mapper");
    }

    @Override
    public T getOne(Long id) {
        Objects.requireNonNull(id);
        T model = this.baseMapper.selectById(id);
        if (Objects.isNull(model)) {
            log.warn("【SQL单个对象查询】查询结果为空:{}=[{}]", this.modelClass.getSimpleName(), id);
        }

        return model;
    }


    @Override
    public Long save(T model) {
        Objects.requireNonNull(model);
        this.baseMapper.insert(model);
        return model.getId();
    }

    @Override
    public Long update(T model) {
        Objects.requireNonNull(model);
        Map<String, Object> whereMap = CommonUtils.getFieldVals(model);
        if (CollectionUtils.isEmpty(whereMap)) {
            log.warn("【SQL更新】查询条件为空：{}={}", this.modelClass.getSimpleName(), whereMap);
            throw new BusinessException(CustomStatusEnum.BAD_REQUEST.getValue(), "【SQL更新】查询条件为空：where=" + whereMap);
        } else {
            return this.baseMapper.updateById(model);
        }
    }


    @Override
    public Long deleteById(Long id) {
        Objects.requireNonNull(id);
        log.info("【SQL删除】 条件:{}={}",this.modelClass.getSimpleName(), id);
        return this.baseMapper.deleteById(id);
    }
}
